package com.lr.transfer.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.lr.transfer.component.ResourceComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * @author lr
 * @since 2018/9/28 15:35
 */
@RestController
@Slf4j
public class DownLoadController {

    /**
     * 下载文件
     *
     * @return
     */
    @PostMapping("/lr/downLoad")
    public void downLoad(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String filename = request.getParameter("filename");
        log.info("filename:{}", filename);
        String[] names = filename.split(",");
        if (names.length == 1) {
            String path = ResourceComponent.getLocation(names[0]);
            downLoadCommon(request, response, FileUtil.file(path));
            return;
        }

        File[] files = new File[names.length];
        for (int i = 0; i < names.length; i++) {
            files[i] = FileUtil.file(ResourceComponent.getLocation(names[i]));
        }
        String filePath = files[0].getParent() + "/" + System.currentTimeMillis() + ".zip";
        File zip = ZipUtil.zip(FileUtil.file(filePath), false, files);
        downLoadCommon(request, response, zip);
    }

    private void downLoadCommon(HttpServletRequest request, HttpServletResponse response, File file) throws Exception {
        response.setContentType("text/html;charset=utf-8");
        // response设置Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
        FileInputStream fis = new FileInputStream(file);
        byte[] buff = new byte[2048];
        int len = 0;
        OutputStream os = response.getOutputStream();
        while ((len = fis.read(buff)) > 0) {
            os.write(buff, 0, len);
        }
        os.close();
        fis.close();
    }

}
